package golf.stockdata.cmdline;

import java.text.DecimalFormat;
import java.text.SimpleDateFormat;

import golf.stockdata.framework.hbmdao.Tfex;
import golf.stockdata.framework.hbmdao.TfexDailyPrice;
import golf.stockdata.framework.util.hbm.HibernateUtil;

import org.apache.log4j.Logger;
import org.hibernate.Session;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Projections;
import org.hibernate.criterion.Property;
import org.hibernate.criterion.Restrictions;

public class GetLatestPriceByContractName {
	
	private static Logger logger = Logger.getLogger(GetLatestPriceByContractName.class);

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		if(args.length <= 0){
			logger.error("Error, needs TFEX contract name");
			System.exit(9);
		}else{
			
			String contractName = args[0];
			
			logger.debug("Processing:".concat(contractName));
//			Date currentDt = Date.valueOf(new Date(System.currentTimeMillis()).toString());
			
			Session session = HibernateUtil.createHibernatesession();
			
			Tfex tfex = (Tfex) session.createCriteria(Tfex.class)
					.add(Restrictions.eq("tfexSymbol", contractName))
					.uniqueResult();
			
			DetachedCriteria maxTs = DetachedCriteria.forClass(TfexDailyPrice.class, "sub")
					.setProjection(Projections.max("id.tfxdpHostTs") )
					.add(Restrictions.eqProperty("sub.id.tfexId","main.id.tfexId"));
			
			TfexDailyPrice dailyPrice = (TfexDailyPrice)session.createCriteria(TfexDailyPrice.class, "main")
					.add(Property.forName("id.tfxdpHostTs").eq(maxTs) )
					.add(Property.forName("id.tfexId").eq(tfex.getId().getTfexId()) )
					.uniqueResult();

			//new DecimalFormat("#.##").format(output.getRunningBalance())
			
			if(dailyPrice != null){
				
				DecimalFormat amountFormatter = new DecimalFormat("#.##");
				SimpleDateFormat dtFormat = new SimpleDateFormat("yyyy-MM-dd");
				SimpleDateFormat tsFormat = new SimpleDateFormat("HH:mm:ss");
				
				logger.info(
						dtFormat.format(dailyPrice.getId().getTfxdpHostTs())
						+ "|"
						+ tsFormat.format(dailyPrice.getId().getTfxdpHostTs())
						+ "|"
						+ amountFormatter.format(dailyPrice.getTfxdpBidPrice().doubleValue())
						+ "|"
						+ amountFormatter.format(dailyPrice.getTfxdpHighPrice().doubleValue())
						+ "|"
						+ amountFormatter.format(dailyPrice.getTfxdpLastPrice().doubleValue())
						+ "|"
						+ amountFormatter.format(dailyPrice.getTfxdpLowPrice().doubleValue())
						+ "|"
						+ amountFormatter.format(dailyPrice.getTfxdpOfferPrice().doubleValue())
						+ "|"
						+ amountFormatter.format(dailyPrice.getTfxdpOpenPrice().doubleValue())					
						);
				
			}else{
				logger.info("none");
			}
			
			session.close();

		}
	}

}
